<?php namespace App\Http\Controllers\Api;

use App\Exceptions\MessageException;
use App\Exceptions\NotFoundException;
use App\Exceptions\SecurityException;
use App\Http\Requests\ChangePasswordRequest;
use App\Http\Requests\ChangeUserInfoRequest;
use App\Images;
use App\Message;
use App\Services\MessageManager;
use App\UserCreate;
use App\UserInfo;
use App\User;
use App\UserWork;
use Illuminate\Auth\Guard;
use Hash;
use Illuminate\Support\Facades\Input;

class MeController extends ApiController
{
    public function getUserInfo(Guard $guard)
    {
        if($guard->guest())
            throw new SecurityException(SecurityException::LoginFirst);

        /** @var User $user */
        $user = $guard->user();
        if(!$user)
            throw new NotFoundException(NotFoundException::UserNotFound);

        $userInfo = $user->userInfo;
        if(!$userInfo)
            throw new NotFoundException(NotFoundException::UserInfoNotFound);

        return $this->buildResponse(trans('api.me.get_user_info.success',$userInfo));
    }

    public function setInterviewMessage(Guard $guard)
    {
        $toUserId    = Input::get('user_id');
        $toProjectId = Input::get('project_id');
        if($guard->guest())
            throw new SecurityException(SecurityException::LoginFirst);

        /** @var User $user */
        $user = $guard->user();
        $toUser = User::find($toUserId);
        if(!$toUser)
            throw new NotFoundException(NotFoundException::UserNotFound);

        $lastMessage = Message::whereUserId($user->id)->whereToUserId($toUserId)->whereIsRead(0)->first();
        if($lastMessage)
            throw new MessageException(MessageException::MessageIsExists);

        MessageManager::sendSystemMessageToUser($user->id,$toUserId,$toProjectId,'meet.InvestorMeetCreater');

        return $this->buildResponse(trans('api.set_interview_message.success'));
    }

    public function getSystemMessage(Guard $guard)
    {
        if($guard->guest())
            throw new SecurityException(SecurityException::LoginFirst);

        /** @var User $user */
        $user = $guard->user();
        if(!$user)
            throw new NotFoundException(NotFoundException::UserNotFound);

        $systemMsgs = $user->message;
        foreach($systemMsgs as $systemMsg)
        {
            if($systemMsg->type == 'SystemMessage'){

            }
        }
        return false;

    }

    public function EditUserInfo(Guard $guard,ChangeUserInfoRequest $request){
        //判断用户是否登录
        if($guard->guest()) throw new SecurityException(SecurityException::LoginFirst);

        //获取用户的数据
        $currentUser = $guard->user();
        if(!$currentUser) throw new SecurityException(SecurityException::NoPermission);

        //判断用户数据是否存在
        /** @var User $user */
        $user = User::find($currentUser->id);
        if(!$user) throw new NotFoundException(NotFoundException::UserNotFound);

        $realname   = $request -> get('realname');        //用户名
        $wechat     = $request -> get('wechat');          //微信
        $weibo      = $request -> get('weibo');           //微博
        $maimai     = $request -> get('maimai');          //脉脉
        $edu_school = $request -> get('edu_school');      //毕业学校
        $position   = $request -> get('position');        //职位
        $user_desc  = $request -> get('user_desc');       //个人介绍
        $email      = $request -> get('email');
        $roles      = Input::get('roles');
        $photo_id   = Input::get('photoid');
        $province   = Input::get('province');             //省份
        $city       = Input::get('city');                 //城市
        $town       = Input::get('town');                 //区 县

        $userId = $currentUser->id;
        $userInfo = UserInfo::whereUserId($userId);
        if($userInfo->exists()){
            $userInfo = UserInfo::whereUserId($currentUser->id)->first();
        }else {
            $userInfo = new UserInfo();
        }

        if(!is_null($realname))$userInfo->realname = $realname;
        if(!is_null($userId))$userInfo->user_id = $userId;
        if(!is_null($province))$userInfo->province = $province;
        if(!is_null($city))$userInfo->city = $city;
        if(!is_null($town))$userInfo->town = $town;
        if(!is_null($wechat))$userInfo->wechat = $wechat;
        if(!is_null($weibo))$userInfo->weibo = $weibo;
        if(!is_null($maimai))$userInfo->maimai = $maimai;
        if(!is_null($edu_school))$userInfo->edu_school = $edu_school;
        if(!is_null($position))$userInfo->position = $position;
        if(!is_null($user_desc))$userInfo->user_desc = $user_desc;
        if(!is_null($email))$user->email = $email;
        if(!is_null($photo_id))$userInfo->photo_id = $photo_id;

        $userInfo->save();
        $user->save();

        $userInfo = UserInfo::whereUserId($userId)->first();

        $userInfo->user_x_roles()->attach($roles);
        $user_roles = $userInfo->user_x_roles()->get();

        foreach($user_roles as $user_role){
            if(!in_array($user_role->id,$roles)){
                $userInfo->user_x_roles()->detach($user_role->id);
            }
        }

        return $this->buildResponse(trans('api.user.edit_me_info.success'),$userInfo);
    }

    /**
     * @param Guard $guard
     * @param ChangeUserInfoRequest $request
     * @return \Illuminate\View\View|\Symfony\Component\HttpFoundation\Response
     * @throws NotFoundException
     * @throws SecurityException
     */
    public function EditUserpass(Guard $guard,ChangeUserInfoRequest $request)
    {
        //判断用户是否登录
        if($guard->guest()) throw new SecurityException(SecurityException::LoginFirst);

        //获取用户的数据
        $currentUser = $guard->user();
        if(!$currentUser) throw new SecurityException(SecurityException::NoPermission);

        //判断用户数据是否存在
        $user = User::find($currentUser->id);
        if(!$user) throw new NotFoundException(NotFoundException::UserNotFound);

        //修改密码
        $password       = $request->get('password');
        if(!$password){
            throw new SecurityException(SecurityException::PasswordNotMatch);
        }
        $user->password = bcrypt($password);
        $user->save();

        return $this->buildResponse(trans('api.auth.EditUserPassword.success'),$user);
    }

    public function getMessage(Guard $guard)
    {
        if($guard->guest())
            throw new SecurityException(SecurityException::LoginFirst);

        /** @var User $user */
        $user = $guard->user();
        if(!$user)
            throw new NotFoundException(NotFoundException::UserNotFound);

        $messages = Message::whereToUserId($user->id)->whereIsRead(0)->get();
        foreach($messages as $message){
            $message["toUserInfo"] = UserInfo::whereUserId($message->to_user_id)->first();
        }

        return $this->buildResponse(trans('api.me.getMessage.success'),$messages);
    }

    public function setUserCreate(Guard $guard)
    {
        $company    = Input::get('company');
        $position   = Input::get('position');
        $start_time = Input::get('create_start_time');
        $end_time   = Input::get('create_end_time');

        if($guard->guest())
            throw new SecurityException(SecurityException::LoginFirst);

        $user = $guard->user();

        $userCreate = new UserCreate();
        $userCreate->user_id    = $user->id;
        $userCreate->company    = $company;
        $userCreate->position   = $position;
        $userCreate->start_time = $start_time;
        $userCreate->end_time   = $end_time;
        $userCreate->save();

        $userCreate->start_time = date('Y-m-d',strtotime($userCreate->start_time));
        $userCreate->end_time   = date('Y-m-d',strtotime($userCreate->end_time));

        return $this->buildResponse(trans('api.me.setUserCreate.success'),$userCreate);

    }

    public function setUserWork(Guard $guard)
    {
        $company    = Input::get('company');
        $position   = Input::get('position');
        $start_time = Input::get('work_start_time');
        $end_time   = Input::get('work_end_time');

        if($guard->guest())
            throw new SecurityException(SecurityException::LoginFirst);

        $user = $guard->user();

        $userWork = new UserWork();
        $userWork->user_id    = $user->id;
        $userWork->company    = $company;
        $userWork->position   = $position;
        $userWork->start_time = $start_time;
        $userWork->end_time   = $end_time;
        $userWork->save();

        $userWork->start_time = date('Y-m-d',strtotime($userWork->start_time));
        $userWork->end_time   = date('Y-m-d',strtotime($userWork->end_time));

        return $this->buildResponse(trans('api.me.setUserWork.success'),$userWork);
    }

    public function checkOldPassword(Guard $guard){
        if($guard->guest())
            throw new SecurityException(SecurityException::LoginFirst);

        /** @var User $user */
        $user = $guard->user();
        if(!$user)
            throw new NotFoundException(NotFoundException::UserNotFound);

        $oldPassword = Input::get('old_password');

        if(!Hash::check($oldPassword,$user->password))
            throw new SecurityException(SecurityException::PasswordNotMatch);

        return $this->buildResponse(trans('api.me.check_old_password.success'), $user);
    }

    public function changePassword(Guard $guard,ChangePasswordRequest $request)
    {
        if($guard->guest())
            throw new SecurityException(SecurityException::LoginFirst);

        /** @var User $user */
        $user = $guard->user();
        if(!$user)
            throw new NotFoundException(NotFoundException::UserNotFound);

        $oldPassword = $request->get('old_password');
        $newpassword = $request->get('new_password');

        if(!Hash::check($oldPassword,$user->password))
            throw new SecurityException(SecurityException::PasswordNotMatch);

        $user->password = bcrypt($newpassword);
        $user->save();

        return $this->buildResponse(trans('api.me.change_password.success'), $user);
    }
}